package org.txazo.blog.commons.search;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.txazo.blog.bean.BlogIndex;

public class LuceneServiceImpl implements LuceneService {

	private static final String indexPath = "D:/index";
	private static Directory directory = null;
	private IndexWriter writer = null;

	public static IndexWriter getIndexWriter(Directory directory)
			throws IOException {
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_44);
		IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_44,
				analyzer);

		return new IndexWriter(directory, config);
	}

	@Override
	public void addIndex(BlogIndex blogIndex) {
		try {
			directory = FSDirectory.open(new File(indexPath));
			writer = getIndexWriter(directory);

			Document doc = new Document();
			doc.add(new StringField("id", blogIndex.getId().toString(),
					Store.YES));
			doc.add(new StringField("memberId", blogIndex.getMemberId()
					.toString(), Store.YES));
			doc.add(new TextField("title", blogIndex.getTitle(), Store.YES));
			doc.add(new TextField("content", blogIndex.getContent(), Store.YES));

			writer.addDocument(doc);
			writer.commit();
			System.out.println("添加记录(id=" + blogIndex.getId() + ")成功");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void deleteIndex(BlogIndex blogIndex) {
		try {
			directory = FSDirectory.open(new File(indexPath));
			writer = getIndexWriter(directory);

			IndexReader reader = DirectoryReader.open(directory);
			Query query = new TermQuery(new Term("id", blogIndex.getId()
					.toString()));
			writer.deleteDocuments(query);
			writer.commit();
			reader.close();
			System.out.println("删除id为" + blogIndex.getId() + "的记录成功");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void updateIndex(BlogIndex blogIndex) {
		try {
			directory = FSDirectory.open(new File(indexPath));
			writer = getIndexWriter(directory);

			Document doc = new Document();
			doc.add(new StringField("id", blogIndex.getId().toString(),
					Store.YES));
			doc.add(new StringField("memberId", blogIndex.getMemberId()
					.toString(), Store.YES));
			doc.add(new TextField("title", blogIndex.getTitle(), Store.YES));
			doc.add(new TextField("content", blogIndex.getContent(), Store.YES));

			writer.updateDocument(new Term("id", blogIndex.getId().toString()),
					doc);

			writer.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public int findIndexByCount() {
		int total = 0;
		try {
			Directory directory = FSDirectory.open(new File(indexPath));
			IndexReader reader = DirectoryReader.open(directory);
			total = reader.numDocs();
			reader.close();
			directory.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return total;
	}

	public List<BlogIndex> queryForIndex(String keyword) {
		List<BlogIndex> list = new ArrayList<BlogIndex>();
		try {
			directory = FSDirectory.open(new File(indexPath));

			IndexReader reader = DirectoryReader.open(directory);
			IndexSearcher search = new IndexSearcher(reader);

			// Query query=new TermQuery(new Term(field, searchText));

			QueryParser parser = new QueryParser(Version.LUCENE_44, "content",
					new StandardAnalyzer(Version.LUCENE_44));
			Query query = parser.parse(keyword);

			TopDocs topDocs = search.search(query, 10000);
			ScoreDoc[] scoreDocs = topDocs.scoreDocs;
			System.out.println("本次命中数据:" + scoreDocs.length);
			for (int i = 0; i < scoreDocs.length; i++) {
				int doc = scoreDocs[i].doc;
				Document document = search.doc(doc);

				BlogIndex blogIndex = new BlogIndex();
				blogIndex.setId(Integer.valueOf(document.get("id")));
				blogIndex
						.setMemberId(Integer.valueOf(document.get("memberId")));
				blogIndex.setTitle(document.get("title"));
				blogIndex.setContent(document.get("content"));

				list.add(blogIndex);
			}

			reader.close();
			directory.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public static void main(String[] args) {
		LuceneService luceneService = new LuceneServiceImpl();
		// BlogIndex blogIndex1 = new BlogIndex(1, 10001, "txazo1", "加载文档");
		// BlogIndex blogIndex2 = new BlogIndex(2, 10002, "txazo2", "取出档案");
		// BlogIndex blogIndex3 = new BlogIndex(3, 10003, "txazo3", "获取文档");
		// BlogIndex blogIndex4 = new BlogIndex(4, 10004, "txazo4", "取出手机");
		// luceneService.addIndex(blogIndex1);
		// luceneService.addIndex(blogIndex2);
		// luceneService.addIndex(blogIndex3);
		// luceneService.addIndex(blogIndex4);

		List<BlogIndex> list = luceneService.queryForIndex("出");
		for (BlogIndex blogIndex : list) {
			System.out.println(blogIndex);
		}
	}

}
